<template>
  <!-- 身份证上传:
  <upload-idcard
    :disabled="!isEdit"
    @updateImage="updateImageIdCardCopy"
    @updateData="upDateDataFront"
    :editImage="form.idCardCopy"
    :side="'front'"
    :fileTypes="fileTypes"
    :ltSize="1"
  >
  </upload-idcard>

  属性
  :disabled 分为两种：一种只有放大按钮，另一种是添加可删除按钮
  editImage 是编辑状态下的回显图片
  side      分为两种：front是人像面，back是国徽面
  fileTypes 是上传图片类型数组['JPEG', 'JPG', 'PNG']
  ltSize    是限制图片大小

  事件
  updateImage 参数：图片地址
  updateData  参数：后台返回数据
   -->
  <div class="uploadBox">
    <img v-if="attachmentUrl" :src="attachmentUrl" class="picCover" alt="" />
    <div class="el-upload-list__item-actions" v-show="attachmentUrl">
      <span
        class="el-upload-list__item-preview"
        style="margin-right: 0.1rem"
        @click="handlePictureCardPreview()"
      >
        <i class="el-icon-zoom-in"></i>
      </span>
      <span
        v-if="!disabled"
        class="el-upload-list__item-preview"
        @click="handleRemove()"
      >
        <i class="el-icon-delete"></i>
      </span>
    </div>

    <el-upload
      class="picUpload"
      ref="picUpload"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      v-show="!attachmentUrl"
      v-model="attachmentUrl"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="handleUpload"
    >
      <div class="pic-uploader-icon" v-if="side == 'front'">
        <img
          class="background"
          src="../../../../assets/images/idCard_front.png"
          alt=""
        />
        <div class="uploadAdd">
          <svg-icon
            iconClass="upload_add"
            style="font-size: 0.56rem"
          ></svg-icon>
          <div class="text">请上传头像面</div>
        </div>
      </div>
      <div class="pic-uploader-icon" v-else>
        <img
          class="background"
          src="../../../../assets/images/idCard_back.png"
          alt=""
        />
        <div class="uploadAdd">
          <svg-icon
            iconClass="upload_add"
            style="font-size: 0.56rem"
          ></svg-icon>
          <div class="text">请上传国徽面</div>
        </div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
export default {
  name: 'DlUploadSingle',
  props: {
    // 不能删除：只能放大
    disabled: {
      type: Boolean,
      default: false,
    },
    // 身份证正反面
    side: {
      type: String,
      default: 'front',
    },
    // 编辑回显的照片
    editImage: {
      type: String,
      default: '',
    },
    fileTypes: {
      type: Array,
      default: () => [],
    },
    ltSize: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      attachmentUrl: '',
      fileList: [],
      limit: 1,
      loadingInstance: null,
    }
  },
  watch: {
    editImage() {
      this.attachmentUrl = this.editImage
    },
  },
  methods: {
    beforeUpload(file) {
      let fileType = file.name.split('.').pop()
      if (this.fileTypes.indexOf(fileType.toUpperCase()) > -1) {
        if (this.ltSize && file.size > this.ltSize * 1024 * 1024) {
          this.$message({
            type: 'error',
            message: `文件不能超过${this.ltSize}M`,
          })
          return false
        }
        if (this.fileList.length > this.limit) {
          this.$message({
            type: 'error',
            message: '文件超出限制数量',
          })
          return false
        }
        this.loadingInstance = Loading.service({
          fullscreen: true,
          spinner: 'el-icon-loading',
          text: '文件上传中...',
        })
      } else {
        this.$message({
          type: 'error',
          message: `请上传${this.fileTypes.toString()}类型的文件`,
        })
        return false
      }
    },
    handleUpload(data) {
      try {
        let file = data.file
        let formData = new FormData()
        formData.append('file', file)
        //图片验证通过才调用接口
        this.$http
          .post(
            this.$API.baseApi.idIdentification + '?side=' + this.side,
            formData
          )
          .then((res) => {
            this.$nextTick(() => {
              this.loadingInstance.close()
            })
            if (res.data.code == 200 && res.data.success) {
              // 判断识别是否成功
              let result = res.data.result
              if (!result.scanResult) {
                // 识别失败
                this.handleRemove()
                this.$message.error('图片无法识别，请重新上传')
              } else {
                this.attachmentUrl = result.idCardUrl
                this.$emit('updateImage', this.attachmentUrl)
                if (this.side == 'front') {
                  // 人像面
                  let { realname, idcard } = result
                  this.$emit('updateData', { realname, idcard })
                } else {
                  // 国徽：有效期
                  let { end } = result
                  this.$emit('updateData', { end })
                }
              }
            }
          })
      } catch (e) {
        this.$nextTick(() => {
          this.loadingInstance.close()
        })
        this.handleRemove()
        this.$message({
          type: 'error',
          message: e,
        })
      }
    },
    handlePictureCardPreview() {
      this.$viewerApi({
        images: [this.attachmentUrl],
      })
    },
    handleRemove() {
      this.attachmentUrl = ''
      this.$emit('updateImage', this.attachmentUrl)
      if (this.side == 'front') {
        // 人像面
        this.$emit('updateData', { realname: '', idcard: '' })
      } else {
        // 国徽：有效期
        this.$emit('updateData', { end: '' })
      }
    },
  },
  mounted() {
    this.attachmentUrl = this.editImage
  },
}
</script>

<style lang="scss" scoped>
.uploadBox {
  width: 2.24rem;
  height: 1.5rem;
  position: relative;
}

/deep/ .el-upload--picture-card {
  width: 2.24rem;
  height: 1.5rem;
}

/deep/ .el-upload-list__item-preview {
  width: 0.3rem;
  height: 0.3rem;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 22;
}

/deep/ .el-upload-list__item-actions {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  display: none;
  cursor: pointer;
}
/deep/ .el-icon-zoom-in:before,
/deep/ .el-icon-delete:before {
  font-size: 0.2rem;
  color: #fff;
}
.uploadBox:hover .el-upload-list__item-actions {
  display: flex;
  visibility: visible;
  transition: 1s;
  background: rgba(0, 0, 0, 0.3);
}
.pic-uploader-icon {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  line-height: 1;
  background-color: #f5f5f5;
  border-radius: 0.04rem;
  .background {
    box-sizing: border-box;
    padding: 0.21rem 0.27rem;
    width: 100%;
    height: 100%;
  }
  .uploadAdd {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .text {
    margin-top: 0.1rem;
    font-size: 0.14rem;
    color: #777777;
    height: 0.2rem;
  }
}
</style>